package com.rzt.cft.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Component
public class FileUploadUtil {

    @Value("${file.basePath}")
    private String basePath;

    public  String uploadFile(MultipartFile pFile, String type) {
        // 获取文件后缀名
        String suffix = pFile.getOriginalFilename().substring(pFile.getOriginalFilename().lastIndexOf(".") + 1);
        Date dt = new Date();
        Long time = dt.getTime();
        String originalFilename = time.toString().substring(time.toString().length() - 8,
                time.toString().length()) + "." + suffix;
        if (pFile != null && !pFile.isEmpty()) {
            try {
                File file = new File(basePath + type);
                if (!file.exists()) {
                    file.mkdir();
                }
                FileUtils.copyInputStreamToFile(pFile.getInputStream(), new File(file, originalFilename));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return null;
        }
        return type + "/" + originalFilename;
    }
}
